﻿using System;
using System.ServiceProcess;

namespace ZilLion.Core.TaskManager.Workstation
{
    public class WinServiceHelper
    {
        /// <summary>
        ///     判断是否安装了某个服务
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool IsWindowsServiceInstalled(string serviceName)
        {
            try
            {
                var services = ServiceController.GetServices();
                foreach (var service in services)
                    if (service.ServiceName == serviceName)
                        return true;
                return false;
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        ///     启动某个服务
        /// </summary>
        /// <param name="serviceName"></param>
        public static void StartService(string serviceName)
        {
            try
            {
                var services = ServiceController.GetServices();
                foreach (var service in services)
                    if (service.ServiceName == serviceName)
                    {
                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
                    }
            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        ///     停止某个服务
        /// </summary>
        /// <param name="serviceName"></param>
        public static void StopService(string serviceName)
        {
            try
            {
                var services = ServiceController.GetServices();
                foreach (var service in services)
                    if (service.ServiceName == serviceName)
                    {
                        service.Stop();
                        service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
                    }
            }
            catch
            {
                // ignored
            }
        }


        /// <summary>
        ///     判断某个服务是否启动
        /// </summary>
        /// <param name="serviceName"></param>
        public static bool IsStart(string serviceName)
        {
            var result = true;
            try
            {
                var services = ServiceController.GetServices();
                foreach (var service in services)
                    if (service.ServiceName == serviceName)
                        if (service.Status == ServiceControllerStatus.Stopped
                            || service.Status == ServiceControllerStatus.StopPending)
                            result = false;
            }
            catch
            {
                // ignored
            }
            return result;
        }
    }
}